import React, { memo, useEffect, useState, Suspense } from "react";
import { useDispatch, useSelector, shallowEqual } from "react-redux";
import NavigationWrap from "../../components/navigation";
import { DjRadioWrap } from "./style";
import { DjRadioDetail, djProgram } from "./store/actionType";
import Loading from "@/components/loading";

const DjRadioLeft = React.lazy(() => import("./djRadioLeft"));
const DjRadioRight = React.lazy(() => import("./djRadioRight"));

export default memo(function DjRadio(props) {
  const [pageNum, setPageNum] = useState(1);
  const [a, setA] = useState(0);

  const dispatch = useDispatch();

  useEffect(() => {
    dispatch(DjRadioDetail(props.location.search.split("=")[1]));
    dispatch(
      djProgram(props.location.search.split("=")[1], 100, (pageNum - 1) * 100)
    );
    setA(0);
  }, [dispatch, props, pageNum]);

  const { djRadioDetails, djPrograms } = useSelector(
    (state) => ({
      djRadioDetails: state.getIn(["djradio", "djRadioDetails"]),
      djPrograms: state.getIn(["djradio", "djPrograms"]),
    }),
    shallowEqual
  );

  useEffect(() => {
    setA(1);
  }, [djRadioDetails]);

  const categoryId =
    djRadioDetails.data !== undefined ? djRadioDetails.data.categoryId : "";
  const programCount =
    djRadioDetails.data !== undefined ? djRadioDetails.data.programCount : "";

  const changePage = (page) => {
    setPageNum(page);
  };

  return (
    <DjRadioWrap>
      {a === 1 ? (
        <>
          <NavigationWrap />
          <div className="djRadioFlex wrap-v2">
            <Suspense fallback={<div>loading</div>}>
              <DjRadioLeft
                changePage={changePage}
                page={pageNum}
                total={programCount}
                djProgram={djPrograms}
                data={djRadioDetails.data}
              />
              <DjRadioRight
                catagory={categoryId}
                id={props.location.search.split("=")[1]}
              />
            </Suspense>
          </div>
        </>
      ) : (
        <div className="loading">
          <Loading />
        </div>
      )}
    </DjRadioWrap>
  );
});
